# -*- encoding: utf-8 -*-

"""
@File:      package.py
@Time:      2022/08/15 16:18:47
@Author:    zhangtaibo.ztb
@Version:   1.0
@Contact:   zhangtaibo.ztb@alibaba-inc.com
@License:   Mulan PSL v2
"""

from common.sysinfo import SysInfo

class PackageManager():
    """
    Common def for package manager.
    """

    def __init__(self):
        self.cmd = SysInfo.cmd()

    def skip(self, message=None):
        raise exceptions.TestSkipError(message)

    def setup_rpm_install(self, pkg_name, host="local"):
        rpm_flag = {}
        rpms = pkg_name.split()
        for rpm in rpms:
            cmdline = "rpm -q %s" % rpm
            ret_c, ret = self.cmd(cmdline, host, ignore_status=True)
            if ret_c is not 0:
                ret_c, ret = self.cmd("yum info %s" % rpm, ignore_status=True)
                if ret_c is not 0:
                    self.skip("%s is not available." % rpm)
                cmdline = "yum install %s -y" % rpm
                self.cmd(cmdline, host)
                rpm_flag[rpm] = 1
            else:
                cmdline = "yum update %s -y" % rpm
                self.cmd(cmdline, host)
                rpm_flag[rpm] = 0
        return rpm_flag
    
    def rpm_uninstall(self, rpm_flag, host="local"):
        rpms = ""
        for rpm in rpm_flag.keys():
            if rpm_flag[rpm] is 1:
                rpms = rpms + " " + rpm
        if rpms != "":
            cmdline = "yum erase %s -y" % rpms
            self.cmd(cmdline, host)
